﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ERPStudio;
using System.Data.SqlClient;
using System.Data.Sql;
using System.Threading;


namespace ResUma
{
    public partial class RecalculSalariiFrm : FrmCard
    {
        private delegate void DisplayInfoDelegate(string Text);
        public SqlConnection con = null;
        private Int16 AnulCurent = 0;
        private Int16 LunaCurenta = 0;

        private Boolean isExecuting;

        private void DisplayStatus(String Text)
        {
            this.label1.Text = Text;
            Application.DoEvents();
            if (Text.Contains("[10001]"))
            {
                GrilaFrm frm = new GrilaFrm(ModuleInfo, 1);
                //frm.MdiParent = this.MdiParent;
                frm.ShowDialog();
            }
            /// procent de vechime negativ - data calcul vechime ulterior perioadei curente!
            if (Text.Contains("[10002]"))
            {
                String[] idp = Text.Split(new Char[] {'{', '}'});
                if(idp.Length>=3)
                {
                    PersonalFrm frm2 = new PersonalFrm(ModuleInfo, Convert.ToInt32(idp[1]));
                    //frm.MdiParent = mdiForm;
                    frm2.ShowDialog();
                }
            }

        }

        private void DisplayResults(string Text)
        {
            this.label1.Text = Text;
            DisplayStatus("Gata - fara erori!");
        }

        public RecalculSalariiFrm(ModuleClass mc):base(mc)
        {
            InitializeComponent();
            workConnString = "ESRPConnectionString";
        }

        private void RecalculSalariiFrm_Load(object sender, EventArgs e)
        {
            con = DeschideConexiune(workConnString, true, 0);
            Object ret = GetSetupValue("ResUmaSetup", "AnulCurent", ModuleInfo.CodUnitate, con);
            /// nu a fost configurat modulul
            /// 
            while (ret == null)
            {
                MessageBox.Show("Modulul Resurse Umane nu a fost configurat. \nVa rugam sa-l configurati!",
                        "Eroare",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Hand);
                ResUmaSetupFrm frm = new ResUmaSetupFrm(ModuleInfo);
                frm.ShowDialog();
                ret = GetSetupValue("ResUmaSetup", "AnulCurent", ModuleInfo.CodUnitate, con);
            }
            AnulCurent = (Int16)ret;
            ret = GetSetupValue("ResUmaSetup", "LunaCurenta", ModuleInfo.CodUnitate, con);
            LunaCurenta = (Int16)ret;

            SetInfoLunaAnul(LunaCurenta.ToString() + "," + AnulCurent.ToString());
            AddButton("Start", global::ERPStudio.Properties.Resources._001_39, Start, ToolStripItemAlignment.Right, true);
        }

        private void Start(object sender, EventArgs e)
        {
            if (isExecuting)
            {
                MessageBox.Show(this,
                    "Se executa o procedura de recalcul! va rugam asteptati pana la finalizare.");
            }
            else
            {
                SqlCommand command = null;
                try
                {
                    DisplayResults("");
                    DisplayStatus("Connecting...");
                    string commandText = "resuma_CalculSalarii";
                    if(con.State!= System.Data.ConnectionState.Open)
                        con =DeschideConexiune(workConnString,0);
                    command = new SqlCommand(commandText, con);
                    command.CommandTimeout = 0;
                    command.CommandType = CommandType.StoredProcedure;
                    command.Parameters.Add(new SqlParameter("@_Anul",AnulCurent));
                    command.Parameters.Add(new SqlParameter("@_Luna",LunaCurenta));
                    command.Parameters.Add(new SqlParameter("@_CodUnitate",ModuleInfo.CodUnitate));
                    command.Parameters.Add(new SqlParameter("@_IDPersoanaSelectata",-1));
                    SqlNotificationRequest request = new SqlNotificationRequest();

                    DisplayStatus("Recalcul Salarii...");
                    isExecuting = true;
                    // Although it is not required that you pass the 
                    // SqlCommand object as the second parameter in the 
                    // BeginExecuteNonQuery call, doing so makes it easier
                    // to call EndExecuteNonQuery in the callback procedure.
                    AsyncCallback callback = new AsyncCallback(HandleCallback);
                    command.BeginExecuteNonQuery(callback, command);



                }
                catch (Exception ex)
                {
                    isExecuting = false;
                    DisplayStatus(string.Format("Gata (ultima eroare: {0})", ex.Message));
                    if (con != null)
                    {
                        InchideConexiune(con);
                    }
                }
            }            
        }

       


        private void HandleCallback(IAsyncResult result)
        {
            try
            {
                SqlCommand command = (SqlCommand)result.AsyncState;
                int rowCount = command.EndExecuteNonQuery(result);
                string rowText = " rows affected.";
                if (rowCount == 1)
                {
                    rowText = " row affected.";
                }
                rowText = rowCount + rowText;
                DisplayInfoDelegate del = new DisplayInfoDelegate(DisplayResults);
                this.Invoke(del, rowText);

            }
            catch (Exception ex)
            {
                 this.Invoke(new DisplayInfoDelegate(DisplayStatus),
                 String.Format("Gata (ultima eroare: {0}", ex.Message));

                 

            }
            finally
            {
                isExecuting = false;
                if (con != null)
                {
                    InchideConexiune(con);
                }
            }
        }

        private void RecalculSalariiFrm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (isExecuting)
            {
                MessageBox.Show(this, "Va rugam asteptati finalizare procedurii de recalcul!");
                e.Cancel = true;
            }
        }


    }
}
